//
//  MenuDataProvider.m
//  TUMensa
//
//  Created by Martin Poehlmann on 4/7/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "MenuDataProvider.h"
#import "DailyMenu.h"

@implementation MenuDataProvider

-(id)init
{
    [super init];
    menues = nil;
    startRange = endRange = index = -1;
    return self;
}

-(BOOL)isEmpty
{

    return startRange == -1;
}

-(int)count
{
    if([self isEmpty])
        return 0;
    
    return endRange - startRange + 1;
}

-(BOOL)hasNextItem
{
    return index < endRange;
}

-(BOOL)hasPrevItem
{
    return index > startRange;
}

-(void)next
{
    if ([self hasNextItem])
        index++;
}

-(void)prev
{
    if ([self hasPrevItem])
        index--;
}

-(DailyMenu *)getCurrentMenu
{
    if ([self isEmpty])
        return nil;
    
    return [menues objectAtIndex:index];
}

-(void) selectToday
{
    
    NSDate *d = [[[NSDate alloc] init] autorelease];
    NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
    [formatter setDateFormat:@"dd.MM.yyyy"];
    
    NSDate *menuDate = nil;
    // Find index which matches today
    index=0;
    do {
        
        DailyMenu* dm = [menues objectAtIndex:index];
        menuDate = [formatter dateFromString:dm.dateString];
        index++;
        
            
    }while ([menuDate compare:d]!=NSOrderedDescending);
    index-=2;
}

-(void)loadData
{
    if (menues == nil)
        menues = [[NSMutableArray alloc]init];
    else
        [menues removeAllObjects];
    
    // TODO real data
    /*
    DailyMenu *dm = [[[DailyMenu alloc] initWithDateString:@"Today"] autorelease];
    
    [dm addMeal:[[[Meal alloc] initWithName:@"Gericht 1 Gericht 1 Gericht 1 Gericht 1 Gericht 1 Gericht 1" andPrice:@"1.00€"] autorelease]];
    [dm addMeal:[[[Meal alloc] initWithName:@"Gericht 2" andPrice:@"2.00€"] autorelease]];
    [dm addMeal:[[[Meal alloc] initWithName:@"Gericht 3" andPrice:@"3.00€"] autorelease]];
    
    [menues addObject:dm];
    
    
    dm = [[[DailyMenu alloc] initWithDateString:@"Tomorrow"] autorelease];
    
    [dm addMeal:[[[Meal alloc] initWithName:@"Gericht 4" andPrice:@"1.00€"] autorelease]];
    [dm addMeal:[[[Meal alloc] initWithName:@"Gericht 5" andPrice:@"2.00€"] autorelease]];
    [dm addMeal:[[[Meal alloc] initWithName:@"Gericht 6" andPrice:@"3.00€"] autorelease]];
    
    [menues addObject:dm];
    */
    
    MensaParser *parser = [[MensaParser alloc] init];
    [parser parseXML:@"http://services.songbook.me/mensa/"];
    menues = parser.menu;
    [menues retain];
     
    
    
    int count = [menues count];
    if (count == 0)
    {
        startRange = endRange = index = -1;
    }
    else
    {
        startRange = 0;
        [self selectToday];
        endRange = count - 1;
    }
}

@end
